//
//  MNDCarAssessHistoryViewController.m
//  minidai
//
//  Created by Vitas on 2018/7/5.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDCarAssessHistoryViewController.h"
#import "MNDCarAssessHistoryCell.h"
#import "MNDCarBrandViewController.h"
#import "MNDSelectProvinceAndCityViewController.h"
#import "GpsManager.h"
#import "MNDCarAddressModel.h"
#import "MNDDownLoadFile.h"
#import "MNDAssessModel.h"
#import "MNDAssessWebViewController.h"
#import "SYRefreshControl.h"

#define kMNDCarAssessHistoryCell @"MNDCarAssessHistoryCell"

@interface MNDCarAssessHistoryViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
/* 省份 */
@property (strong, nonatomic) NSString *provinceStr;
/* 城市 */
@property (strong, nonatomic) NSString *cityStr;
/* 模型数组 */
@property (strong, nonatomic) NSMutableArray *carAddressArray;
//当前定位城市id
@property (assign, nonatomic) NSInteger cityAddressId;

@property(nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation MNDCarAssessHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getGpsMsg:) name:@"GPS_Location" object:nil];
    
    kdeclare_weakself;
    [SYRefreshControl configGifMJRefresh:self.tableView refreshType:MJRefreshSupportRefresh beginRefresh:YES timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        [weakSelf loadHistoryData];
    } loadMoreBlock:^{
        
    }];
    [MNDDownLoadFile downLoadFileWithUrl:API_AREA_FILE isArea:YES];
    [MNDDownLoadFile downLoadFileWithUrl:API_CAR_TYPE_FILE isArea:NO];
    //定位
    [[GpsManager sharedGpsManager] getCurrentCity];
    [self getGpsCityId];
    // Do any additional setup after loading the view.
}


#pragma mark - 懒加载
- (NSMutableArray *)carAddressArray {
    if (!_carAddressArray) {
        _carAddressArray = [NSMutableArray array];
    }
    return _carAddressArray;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

//获取当前位置
- (void)getGpsMsg:(NSNotification *)noti
{
    self.provinceStr = noti.userInfo[@"provinceName"];
    self.cityStr = noti.userInfo[@"cityName"];
    for (MNDCarAddressModel *firstModel in self.carAddressArray) {
        for (MNDCarProvinceModel *provinceModel in firstModel.province) {
            if ([provinceModel.pro_name isEqualToString:self.cityStr]) {
                self.cityAddressId = provinceModel.area_id;
            }else {
                for (MNDCarCityModel *cityModel in provinceModel.citys) {
                    if ([cityModel.area_name isEqualToString:self.cityStr]) {
                        self.cityAddressId = cityModel.area_id;
                    }
                }
            }
        }
    }
}


#pragma mark - 加载数据
- (void)loadHistoryData {
    kdeclare_weakself;
    [APIManager sendRequestWithURL:API_CAR_ASSESS_RECORD parameters:[MNDSign signedParam] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakSelf.dataArray = [MNDAssessModel mj_objectArrayWithKeyValuesArray:responseModel.data];
            [weakSelf.view configBlankPage:SYBlankPageTypeNoData hasData:weakSelf.dataArray.count reloadButtonBlock:nil];
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:self.dataArray.count];
            [weakSelf.tableView reloadData];
        }else {
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

//获取GPS定位城市ID
- (void)getGpsCityId {
    //Cache目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"area_list.json"];
    //加载JSON文件
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    if(!data) {
        NSLog(@"文件未找到");
        //重新下载
        [MNDDownLoadFile downLoadFileWithUrl:API_AREA_FILE isArea:YES];
        
    }else {
        
        NSError *error;
        
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        //
        self.carAddressArray = [MNDCarAddressModel mj_objectArrayWithKeyValuesArray:jsonArray];
        
    }
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDAssessModel *assessModel = self.dataArray[indexPath.row];
    MNDCarAssessHistoryCell *historyCell = [tableView dequeueReusableCellWithIdentifier: kMNDCarAssessHistoryCell];
    historyCell.assessModel = assessModel;
    return historyCell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MNDAssessModel *assessModel = self.dataArray[indexPath.row];
    //估值
    MNDAssessWebViewController *assessVC = [[MNDAssessWebViewController alloc] init];
    assessVC.title = @"车辆估值";
    NSString *url = [NSString stringWithFormat:@"%@?car_id=%zd&car_name=%@&city_id=%zd&city_name=%@",API_CAR_ASSESS,assessModel.carModelId,assessModel.carModelName,assessModel.areaId,assessModel.areaName];
    assessVC.webViewUrl = url;
    assessVC.cityAddressId = assessModel.areaId;
    assessVC.cityName = assessModel.areaName;
    assessVC.carId = assessModel.carModelId;
    assessVC.carName = assessModel.areaName;
    [self.navigationController pushViewController:assessVC animated:YES];
    
}

- (IBAction)carAssessAction:(UIButton *)sender {
//    MNDSelectProvinceAndCityViewController *areaVC = [UIStoryboard viewControllerWithIdentifier:@"MNDSelectProvinceAndCityViewController"];
//    areaVC.cityAddressId = self.cityAddressId;
//    areaVC.cityName = self.cityStr;
//    [self.navigationController pushViewController:areaVC animated:YES];
    MNDCarBrandViewController *carBrandVC = [UIStoryboard viewControllerWithIdentifier:@"MNDCarBrandViewController"];
    carBrandVC.cityAddressId = self.cityAddressId;
    carBrandVC.cityName = self.cityStr;
    [self.navigationController pushViewController:carBrandVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
